<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"></meta>
    <title>2</title>
</head>
<body>
hello world!
<textarea id="content" ows="400" cols="100" style="margin: 0px; height: 335px; width: 808px;">
</textarea>
<input type="button" value="发送消息" onclick="sendMsg()" />
</body>
<script>
    var socket;
    if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else{
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        index = new WebSocket("ws://localhost:8080/wsHandler/2");
        index.onopen = function() {
            console.log("Socket 已打开");
        };
        //获得消息事件
        index.onmessage = function(msg) {
            console.log(msg.data);
            //发现消息进入
            //开始处理前端触发逻辑
            var ele = document.getElementById("content");
            ele.value = ele.value + '\n' +msg.data;
        };
        //关闭事件
        index.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        index.onerror = function() {
            alert("Socket发生了错误");
            //此时可以尝试刷新页面
        }
        //离开页面时，关闭socket
        //jquery1.8中已经被废弃，3.0中已经移除
        // $(window).unload(function(){
        //     socket.close();
        //});
    }
    function sendMsg(){
        index.send("这是来自客户端的消息1" + location.href + new Date());
        var xmlhttp = new XMLHttpRequest();
        // get方法带参数是将参数写在url里面传过去给后端
        xmlhttp.open("GET", "/socket/socket/push/1", true);
        xmlhttp.send();
    }
</script>
</html>